function showSuccess(callback) {
    $('.complaint_success').show().find('.complaint_close_num').text('3s ')
    var num = 3;
    var timer = setInterval(function() {
        if (num == 1) {
            clearInterval(timer)
            $('.complaint_success').hide()
            callback()
            return
        }
        $('.complaint_success').find('.complaint_close_num').text((num -= 1) + 's ')
    }, 1000)
}
var imgTimer = ''
var companyList = [];

function showImgError(callback) {
    imgTimer && clearTimeout(imgTimer);
    $('.img_error_toast').show()
    imgTimer = setTimeout(function() {
        $('.img_error_toast').hide()
    }, 3000)
}

function changeCompany(key) {

    utils.ajaxPost("/scrm/homepage/last-login-record", {
        memberId: companyList[key].memberId
    }, function(res) {
        $('#company_name').text(companyList[key].companyName.length > 8 ? companyList[key].companyName.substr(0, 8) + '...' : companyList[key].companyName).addClass('change_company')
        $(".header_company_list").hide()
            // var login_info = JSON.parse($.cookie("qqt-login-info"))
            // login_info.member_id = companyList[key].memberId;
            // // utils.setLoginCookie("company-info", companyList[key])
            // utils.setLoginCookie("login-info", login_info, $.cookie("qqt-stayLogin") == "true")
        utils.ajaxGet("/member/member-base-info?" + $.param({
                memberId: companyList[key].memberId
            }), '', function(resp) {
                console.log(resp.data)
                    //$.cookie("member-base-info",JSON.stringify(res.data), { expires: 1, path: '/' })
                utils.setLoginCookie("member-info", resp.data)
                window.location.reload()
                    //   jumpPage(isJump)
            }, function() {

            })
            //  window.layer && layer.closeAll('loading');

    })

}

function getCompanyList() {
    utils.ajaxGet("/scrm/homepage/login-enterprise", {}, function(res) {
            var companyEle = $(".header_company_list").on('click', 'li', function() {
                $(this).addClass('active').siblings().removeClass('active')
                window.layer && layer.load();
                changeCompany($(this).attr('data-key'))

            }).on('click', function(event) {
                var e = arguments.callee.caller.arguments[0] || event; //若省略此句，下面的e改为event，IE运行可以，但是其他浏览器就不兼容

                if (e && e.stopPropagation) {
                    // this code is for Mozilla and Opera
                    e.stopPropagation();

                } else if (window.event) {
                    // this code is for IE
                    window.event.cancelBubble = true;

                }
            })
            if (res.data.length === 0) {
                $(".yidenglu_li").show().children("a:eq(0)").text(JSON.parse($.cookie("qqt-login-info")).phone);
            } else {
                companyList = res.data;
                $.each(res.data, function(k, v) {
                    var ele = $('<li data-key="' + k + '">' + v.companyName + '</li>');

                    if (v.lastLogin === true) {
                        ele.addClass('active')
                        $('#company_name').text(v.companyName.length > 8 ? v.companyName.substr(0, 8) + '...' : v.companyName).addClass('change_company')
                        memberBaseInfoHeader(v.memberId)
                    }

                    companyEle.append(ele)
                })

                if (companyEle.find('.active').length == '0') {
                    changeCompany(0)
                } else {

                }
                $('#company_name').on('click', function() {
                    companyEle.show()
                    setTimeout(function() {
                        companyEle.css({ 'height': 36 * companyList.length + 'px' })
                    }, 100)
                    return false

                })
                $(document).on('click', function() {
                    companyEle.css('height', '0px')
                    setTimeout(function() {
                        companyEle.hide()
                    }, 600)
                })
            }

        })
        //     alert(3)
    $(".weidenglu_li").hide();
    $(".welcome").text("您好！")

    $(".yidenglu_li").show()
    $(".kfrx").hide();

}
$(function() {

    // if ($('.fixRight').length == 0) {
    //     $('body').append('<div class="fixRight"></div>')
    //     $('head').append('<link rel="stylesheet" href="../static/css/navRight.css?v=20211124">')
    // }
    // $(".fixRight").load("../components/navRight.html #rightNav", function() {
    //     $.getScript('../static/js/navRight.js?v=20211124', function() {

    //     });
    // });
    // $('.headerBox').on('click', '#complaint_show', function() {

    //     $('.complain_show_btn').click()
    // })
    getKfPhone() //获取客服电话
        /* 判断dom加载完 填充数据   */
    var flag1 = 0;
    var flag2 = 0;
    var flag3 = 0;

    var flag4 = 0;
    var timerHeader1 = setInterval(function() {

        flag1++
        if (flag1 >= 10) {
            clearInterval(timerHeader1);
            return false
        }
        if ($("#headerBody").length < 1) { //判断是否加载完成

        } else {
            flag1 = 11
            clearInterval(timerHeader1);
            //   alert(3)
            //      alert(2)
            /* 是否登录 */
            if ($.cookie("qqt-access-token")) {

                getCompanyList();
            } else {
                $('.weidenglu_li').show()
            }
            $(".userLink").click(function() {

                if ($.cookie("qqt-access-token")) {
                    window.open("//" + utils.getUserHostName() + "/#" + $(this).attr("data-href"))
                } else {
                    window.open("../login/login.html?forword=" + encodeURIComponent("//" + utils.getUserHostName() + "/#" + $(this).attr("data-href")))
                }

            })
            $("body").on('click', '.rela', function() {

                $(".fblx").show();
            })
            $(document).mouseup(function(e) {
                var pop = $('.fblx');
                if (!pop.is(e.target) && pop.has(e.target).length === 0) {
                    // 可以在这里关闭弹窗
                    $(".fblx").hide();
                }
            });
            $(".fblx>li").click(function(event) {
                    $(".fblx").hide();
                    event.stopPropagation();
                })
                /* 是否登录 */
            $(".loginBtn-forword").click(function() {
                window.open("../login/login.html?forword=" + encodeURIComponent(window.location.href))
            })

            $(".zhuce-forword").click(function() {
                window.open("../login/register.html?forword=" + encodeURIComponent(window.location.href))
            })

            /* 退出登录 */
            $("#login_out").click(function() {
                    utils.clearLoginCookie();
                    window.location.href = "../login/login.html?forword=" + encodeURIComponent(window.location.href)
                })
                /* 退出登录 */

        }
    }, 50)
    var timerHeader2 = setInterval(function() {
        flag2++
        if (flag2 >= 10) {
            clearInterval(timerHeader2);
            return false
        }
        if ($("#searchNav").length < 1) { //判断是否加载完成 /* 搜索框 */

        } else {
            flag2 = 11
            clearInterval(timerHeader2);
            /* 搜索框 */
            $(".searchTab>span").click(function() {
                $(this).addClass("cur").siblings().removeClass("cur")
                if ($(this).text() == "商品") {
                    $("#searchInput1").attr({ "placeholder": "请输入商品关键词进行搜索", "data-id": "1" })
                    getHotword("goods_hotword")
                } else if ($(this).text() == "企业") {
                    $("#searchInput1").attr({ "placeholder": "请输入企业名进行搜索", "data-id": "2" })
                    getHotword("member_hotword")
                } else if ($(this).text() == "采购") {
                    $("#searchInput1").attr({ "placeholder": "请输入采购标题进行搜索", "data-id": "3" })
                    getHotword("oppo_hotword")
                }
            })
            if (window.location.href.indexOf("/search/shop.html") != -1) {
                $(".searchTab>span").eq(1).click()
            } else if (window.location.href.indexOf("/search/business.html") != -1) {
                $(".searchTab>span").eq(2).click()
            } else {
                $(".searchTab>span").eq(0).click()
            }
            if (utils.getUrlParam("keyword")) {
                $("#searchInput1").val(decodeURI(utils.getUrlParam("keyword")))
            }
            $("#searchInput1").keydown(function(event) {
                if (event.keyCode == 13) {
                    $("#searchBtn1").click();
                }
            })
            $("#searchBtn1").click(function() {
                if (!$("#searchInput1").val()) {
                    return false
                }
                switch ($(this).siblings(".searchInput").attr("data-id")) {
                    case "2":
                        window.open("/search/shop.html?keyword=" + encodeURI(encodeURI($(this).siblings(".searchInput").val())))
                        break;
                    case "3":
                        window.open("/search/business.html?keyword=" + encodeURI(encodeURI($(this).siblings(".searchInput").val())))
                            //      window.location.href = 
                        break;
                    default: //都不符合会执行这里
                        window.open("/search/goods.html?keyword=" + encodeURI(encodeURI($(this).siblings(".searchInput").val())))
                            //console.log("/search/goods.html?keyword="+encodeURI($(this).siblings(".searchInput").val()))
                            //    window.location.href = "/search/goods.html?keyword=" + encodeURI(encodeURI($(this).siblings(".searchInput").val()))

                }
            })


            /* 搜索框 */
        }
    }, 50)
    var timerHeader3 = setInterval(function() {
        flag3++
        if (flag3 >= 10) {
            clearInterval(timerHeader3);
            return false
        }
        if ($("#searchNav2").length < 1) { //判断是否加载完成 /* 搜索框 */

        } else {
            flag3 = 11
            clearInterval(timerHeader3);
            /* 搜索框 */
            $('#searchBtn2').click(function() {
                    if ($('#searchInput2').val() != "") {
                        window.location.href = '../search/business.html?keyword=' + encodeURI(encodeURI($('#searchInput2').val()))
                    }
                })
                /* 搜索框 */
        }
    }, 50)

    var timerHeader4 = setInterval(function() {
        flag4++
        if (flag4 >= 10) {
            clearInterval(timerHeader4);
            return false
        }
        if ($("#top_header").length < 1) { //判断是否加载完成 /* 搜索框 */

        } else {
            flag4 = 11
            clearInterval(timerHeader4);
            gettouheader(30); //获取头部图片
        }
    }, 50)



    /*  获取未读站内信 */
    function getNewsList() {
        var query = {
            current: 1,
            size: 3,
            source: 0
        }
        utils.ajaxGet("/b2b-message/notice/system-notices", query, function(res) {
            var str = ''
            if (res.data.records.length < 1) {
                str = '<p class="aglinC">暂无未读消息</p>'
                $("#memberNews").html(str);
                return false;
            }
            $.each(res.data.records, function(index, item) {
                str += '<li data-id="' + item.id + '"><span>' + item.title + '</span><span>' + utils.formatterDateNews(item.createTime) + '</span><span>' + item.categoryName + '</span></li>'
            })
            $("#homeNewsLi").html(str);
            $(".news_num_font").text(res.data.total).show();
            $("#homeNewsLi li").click(function() {
                window.open("//" + utils.getUserHostName() + "/#/user/notice/index/detail?id=" + $(this).attr("data-id"))
            })
        }, function() {

        })
    }

    function getHotword(hotword) {
        //商品搜索词  paramKey=goods_hotword
        //企业搜索词  paramKey=member_hotword
        //商机搜索词  paramKey=oppo_hotword
        var query = {
            clientId: "caigouwang_membercenter",
            paramKey: hotword
        }
        utils.ajaxGet("/blade-system/param-biz/detail", query, function(res) {
            var str = '热门搜索：'
            if (!res.data.paramValue) {
                $("#hotword").html("")
                return false;
            }
            var dataArray = res.data.paramValue.split(",")
            $.each(dataArray, function(index, item) {
                if (hotword == "goods_hotword") {
                    str += '<a rel="nofollow" href="/search/goods.html?keyword=' + encodeURI(encodeURI(item)) + '">' + item + '</a>'
                } else if (hotword == "member_hotword") {
                    str += '<a rel="nofollow" href="/search/shop.html?keyword=' + encodeURI(encodeURI(item)) + '">' + item + '</a>'
                } else {
                    str += '<a rel="nofollow" href="/search/business.html?keyword=' + encodeURI(encodeURI(item)) + '">' + item + '</a>'
                }
            })
            $("#hotword").html(str)
        }, function() {

        })
    }

    //获取客服电话
    function getKfPhone() {
        utils.ajaxGet("/b2b-system/setting/contact", {}, function(res) {
            $(".kefu_phone").html(res.data.phone)
        }, function() {

        })
    }

    // 头部图片
    function gettouheader(type) {
        var query = {
            type: type
        }
        utils.ajaxGet("/b2b-system/setting/banners", query, function(res) {
            if (res.data.length > 0) {
                if (type == 30) {
                    if (res.data.length > 1) {
                        var str = '';
                        $.each(res.data, function(index, item) {
                            str += '<div class="swiper-slide">';
                            if (item.url == '') {
                                str += '<img src="' + item.imageUrl + '" alt=""/>'
                            } else {
                                str += '<a href="' + item.url + '" target="_blank"><img src="' + item.imageUrl + '" alt=""/></a>';
                            }
                            str += '</div>';
                        })
                        $("#top_header").append(str);
                        var mySwiper = new Swiper('.tophead-swiper-container', {
                            loop: true, // 循环模式选项
                            autoplay: 3000,
                            speed: 800,
                            // pagination: '.swiper-pagination',
                            // nextButton: '.swiper-button-next',
                            // prevButton: '.swiper-button-prev',
                        })
                    } else {
                        if (res.data[0].url == '') {
                            $('.top_header').html('<img src="' + res.data[0].imageUrl + '" alt=""/>');
                        } else {
                            $('.top_header').html('<a href="' + res.data[0].url + '" target="_blank"><img src="' + res.data[0].imageUrl + '" alt=""/></a>');
                        }
                    }

                }
            }
        }, function() {

        })
    }


    $('body').on('input', '.count_textarea', function() {
        $(this).siblings('.textarea_count').text($(this).val().length + '/' + $(this).attr('maxlength'))

    })
    $('.headerBox').on('click', '.delete_icon', function() {

        $(this).parents('.complaint_upload_img').remove()
        $('.complaint_upload_label').show();
    })
    $('.headerBox').on('click', '#complaint_show', function() {

        if ($.cookie("member-base-info")) {
            var userInfo = JSON.parse($.cookie("member-base-info"))
            console.log(userInfo)
            $('#r_complaint_phone').val(userInfo.linkmanPhone ? userInfo.linkmanPhone : userInfo.mobile)

        }
        $('.right_nav_complaint_form .delete_icon').click()
        $('#r_complaint_content').val('');
        $('.right_nav_complaint_wrap').show().find('.error').removeClass('error')
        $('.right_nav_complaint_wrap').find('.ly_error_tip').text('')
    })
    $('.headerBox').on('click', '.right_nav_complaint_info_close', function() {
        $('.right_nav_complaint_wrap').hide()

    })
    $('.headerBox').on('change', '#right_nav_complaint_upload', function() {

        var formData = new FormData();

        var test = $(this)[0].files[0]; //或者 $('#test').get(0).files[0]);
        if ($(this)[0].files[0].size / 1024 / 1024 > 5) {
            this.outerHTML = this.outerHTML;
            showImgError()
            return
        }

        formData.append('file', test);
        var self = this;
        $.ajax({
            type: 'POST',
            url: "//" + utils.getHostName() + '/material/upload/file-image',
            data: formData,
            cache: false, //上传文件无需缓存
            processData: false, //用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            success: function(res) {
                //       console.log(res)
                var imgEle = $('<div class="complaint_upload_img complaint_upload_item" ><img src="' + res.data + '" class="r_upload_item"><div class="complaint_upload_img_mask"><img class="delete_icon"  src="../static/img/complanint/delete.png"></div>');
                //  console.log(imgEle)

                // complaint_upload_img
                if ($('.complaint_upload_img').length >= 2) {
                    $('.complaint_upload_label').hide();
                    imgEle.css('margin', 0);
                }

                $(self).before(imgEle)
                self.outerHTML = self.outerHTML;
            },
            error: function(res) {
                self.outerHTML = self.outerHTML;

            }
        })


    })
    $('.headerBox').on('blur', '.right_nav_complaint_wrap input,.right_nav_complaint_wrap textarea', function() {
        //      alert(3)
        vIpnutRight(this)
    })

    function vIpnutRight(ele, type) {
        switch ($(ele).attr("name")) {
            case "r_complaint_content":
                checkRInput($(ele), utils.emptyRegExp)
                    // if($(this).val()){
                    //     findSensitiveword($(this).val(), 'linkman',7)
                    // }
                break;


            case "r_complaint_phone":
                checkRInput($(ele), utils.phoneRegExp, 2)
                break;



        }
    }

    function checkRInput(inputEle, regExpval, phone_type) {
        if (phone_type == 2 && !inputEle.val()) {
            inputEle.parent().next(".ly_error_tip").text("");
            inputEle.removeClass("error")
            inputEle.removeClass("f_error")
            return;
        }
        if (!(regExpval.test(inputEle.val()))) {

            inputEle.parent().next(".ly_error_tip").text(inputEle.attr("data-text"));
            inputEle.addClass("error");

            phone_type === 2 && inputEle.val() !== '' && inputEle.next(".ly_error_tip").text("请填写正确的手机号");
        } else {
            inputEle.parent().next(".ly_error_tip").text("");
            inputEle.removeClass("error")
            inputEle.removeClass("f_error")

        }

    }
    var captcha1 = ''

    function setTx() {
        captcha1 = new TencentCaptcha(utils.captchaAppId, function(res) {

            // res（用户主动关闭验证码）= {ret: 2, ticket: null}
            // res（验证成功） = {ret: 0, ticket: "String", randstr: "String"}
            if (res.ret === 0) {

                window.layer && layer.load();

                var params = {
                    content: $('#r_complaint_content').val(),

                    type: 1,
                    typeSub: 0,
                    linkman: '',
                    phone: $('#r_complaint_phone').val(),
                    pictures: [],

                    ticket: res.ticket,
                    randStr: res.randstr,
                    userIp: ""
                }
                $('.r_upload_item').each(function(k, val) {
                    var imgUrl = $(val).attr('src')
                    var obj = {
                        name: imgUrl.split('/')[imgUrl.split('/').length - 1],
                        url: imgUrl
                    }
                    params.pictures.push(obj)
                })
                console.log(params)
                    //    return;
                utils.ajaxPost('/b2b-system/report/web/report-feedback', params, function(res) {
                    $('#r_complaint_phone').val('');
                    $('#r_complaint_content').val('');
                    $('.right_nav_complaint_wrap').hide();
                    $('.complaint_upload_img').remove();
                    window.layer && layer.closeAll('loading');
                    $('.complaint_upload_label').show();
                    showSuccess(function() {
                        //  window.location.reload()
                    })
                }, function(res) {
                    // targetForm.find(".toast_pop").text(res.msg).show();
                    layer.alert(res.msg)
                    layer.closeAll('loading');
                    return false
                })


            }
        })
    }
    if (!window.TencentCaptcha) {
        $.getScript('https://ssl.captcha.qq.com/TCaptcha.js', function() {
            setTx()
        });
    } else {
        setTx()
    }


    $('.headerBox').on('click', '.r_complaint_submit_btn', function() {
        $('.right_nav_complaint_wrap input,.right_nav_complaint_wrap textarea').blur()
        if ($('.right_nav_complaint_wrap').find(".error").length == 0) {
            captcha1.show();
        } else {

            ///    layer.msg($('.right_nav_complaint_wrap').find(".error").eq(0).parent().next(".ly_error_tip").eq(0).text())
        }
    })


})